<template>
  <div class="content" :style="{width:imgWidth,height:imgHeight}">
    <!-- <img :src="currentImage" class="img" :style="{ transform: `scale(${scale})` }" ref="imgs" /> -->
	 <img :src="$imgUrl1+currentImage.url"  class="img" :style="{ transform: `scale(${scale})` }" ref="imgs"/>
    <canvas ref="markCanvas" tabindex='0'></canvas>
	<!-- <div class="routate" ref="draggableElement">
		<div class="routateboxsetlist">
			<el-select class="questiontypemodel" v-model="questiontypemodel" placeholder="" @change="modeltypetab">
			    <el-option
			      v-for="item in questionlistbox"
			      :key="item.id"
			      :label="item.name"
			      :value="item.id">
			    </el-option>
			</el-select>
			<div class="questionshowhidden">
				<em>题号：</em>
				<img src="../../assets/image/question.jpg" alt="" @click="qiehuanquestion" style="cursor: pointer;">
				<div v-if="questionnumberishow" class="twoinputbox">
					<el-input v-model="startselfQuestionumber"></el-input> - <el-input v-model="endselfQuestionumber"></el-input>
				</div>
				<div v-else class="dangeinput">
					<el-input v-model="selfQuestionumber" type="textarea"></el-input>
				</div>
			</div>
		</div>
		<el-select v-model="questiontype" placeholder="请选择" @change="modeltypetab1">
		    <el-option
		      v-for="item in questionclassifylist"
		      :key="item.id"
		      :label="item.name"
		      :value="item.id">
		    </el-option>
		</el-select>
		<el-button type="primary">{{circleselectionstatus==0?'圈选':circleselectionstatus==1?'圈选中':'取消圈选'}}</el-button>
	</div> -->
  </div>
</template>
<script>
import { mapState } from 'vuex';
import {draw, getJudge,delDraw} from "@/utils/drawCropper"; // 矩形绘制方法
import { get, post, del, put,dele } from '../../api/modelapi.js'
export default {
  name: 'marks',
  props:['imageUrllist','parentData','modelarealistcavans','pagevale',,'drawStatus','scorenumber'],
  data() {
    return {
      // imageUrl: require('../../assets/image/cardmodle.jpg'),
      scale: 1,
      markList: [
	  ], // 标记内容数组
	  isDrawing:false,
	  questiontype:'',
	  questionList:[
	  	{
	  		name:'客观题',
	  		id:6
	  	}
	  ],
	  currentIndex: 0, // 当前图片索引
	  currentImage:{},
	  images:[],
	  value:'第1张',
	  questionlistbox:[
		  {
			  name:'题号/选项横排',
			  id:'1'
		  },
		  {
			  name:'题号/选项竖排',
			  id:'2'
		  },
		  {
			  name:'题号横排/选项竖排',
			  id:'1,2'
		  },
		  {
			  name:'题号竖排/选项横排',
			  id:'2,1'
		  }
	  ],
	  questiontypemodel:'',
	  questionnumberishow:true,
	  startselfQuestionumber:'',
	  endselfQuestionumber:'',
	  selfQuestionumber:'',
	  questionclassifylist:[{name:'单选题',id:1},{name:'多选题',id:2}],
	  questionnumberhor:true,
	  isProcessing: false ,// 防止重复操作
	  questionnumbercon:{
		  optionArrangement: '',
		  questionArrangement: '',
		  examCourseQuestionId: 0,
		  questionRulesId: this.questiontype,
		  includedNumbers: ''
	  },
	  imgWidth:'',
	  imgHeight:'',
	  lastValidValue: null, // 保存上一次的有效输入值
    }
  },
  watch:{
    markList:function (val,oval){
	   this.$emit('updateMarkList', val);
    },
	modelarealistcavans:{
		handler(val,old){
			this.markList = val
			setTimeout(()=>{
				this.initCanvas(2); // 画布初始化
			},1000)

		},
		deep:true
	},
	pagevale(val,oval){
		this.currentImage = this.images[val - 1]; // 更新当前图片
	},
	imageUrllist:{
		handler(val,ova){
			// //console.info(this.pagevale)
			this.images = val
			this.currentImage = val[this.pagevale-1]; // 初始化当前图片
		},
		deep:true
	},
	// 题型
	questiontype(val,old){
	   if (val === this.lastValidValue) {
	     this.$message({
	   	message: '新值和旧值相同',
	   	type: 'warning',
	     });
	     return; // 阻止后续操作
	   }
	   // 允许操作
	   this.isDrawing = true;
	   this.startCrop();
	   	
	   // 更新上一次的有效值
	   this.lastValidValue = val;
	},
	// 题号题型排序
	questiontypemodel(val,old){
		//console.info(val+'----------'+old)
		if (val === this.lastValidValue) {
		  this.$message({
			message: '新值和旧值相同',
			type: 'warning',
		  });
		  return; // 阻止后续操作
		}
			
		// 允许操作
		this.isDrawing = true;
		this.startCrop();
			
		// 更新上一次的有效值
		this.lastValidValue = val;
	},
	//起始题号
	startselfQuestionumber(val,old){
		if (val === this.lastValidValue) {
		  this.$message({
			message: '新值和旧值相同',
			type: 'warning',
		  });
		  return; // 阻止后续操作
		}
			
		// 允许操作
		this.isDrawing = true;
		this.startCrop();
			
		// 更新上一次的有效值
		this.lastValidValue = val;
		
	},
	//结束题号
	endselfQuestionumber(val,old){
		console.log('val:', val, typeof val);
		    console.log('old:', old, typeof old);
		if (val === this.lastValidValue) {
		  this.$message({
			message: '新值和旧值相同',
			type: 'warning',
		  });
		  return; // 阻止后续操作
		}
		// 允许操作
		this.isDrawing = true;
		this.startCrop();
	
		// 更新上一次的有效值
		this.lastValidValue = val;
	},
	// 综合题号
	selfQuestionumber(val,old){
		if (val === this.lastValidValue) {
		  this.$message({
			message: '新值和旧值相同',
			type: 'warning',
		  });
		  return; // 阻止后续操作
		}
		// 允许操作
		this.isDrawing = true;
		this.startCrop();
			
		// 更新上一次的有效值
		this.lastValidValue = val;
	}
  },
  created(){
	 
  },
  computed: {
      ...mapState(['circleselectionstatus']), // 从 Vuex 中获取状态
    },
  mounted() {
	 this.currentImage = this.imageUrllist[this.currentIndex]; // 初始化当前图片
	 this.handleImageLoad();
	 document.addEventListener('customMouseDown', (event)=>{
	   // console.log(event);
	 });
	//  this.questionlistclassify()
  },
  methods: {
	handleImageLoad() {
	    this.initCanvas(1);
	},
	  getDraggableElement() {
	        return this.$refs.draggableElement;
	      },
	  //获取题型列表
	  questionlistclassify(){
		 get('/questionrules/list')
		  .then(res=>{
			  if(res.code==200){
				  this.questionclassifylist = res.data.filter(item=>item.questionType==2)
			  }else{
				 this.$message.error(res.message);  
			  }
		  })
		  .catch(error=>{
			  this.$message.error(error.message); 
		  })
	  },
	  modeltypetab(val){
		  this.isDrawing = true;
		this.$emit('modeltype',val)  
		this.startCrop()
	  },
	  modeltypetab1(val){
		  this.$emit('modeltype',val)  
		  this.isDrawing = true;
		  this.startCrop()
	  },
	  // 验证输入
	      validateInputs() {
	          const validations = [
	              {
	                  condition: !this.questiontypemodel,
	                  message: '请选择题型模板'
	              },
	              {
	                  condition: this.questionnumberishow && 
	                            (!this.startselfQuestionumber || !this.endselfQuestionumber),
	                  message: '请填写题号范围'
	              },
	              {
	                  condition: !this.questionnumberishow && !this.selfQuestionumber,
	                  message: '请填写题号'
	              },
	              {
	                  condition: !this.questiontype,
	                  message: '请选择类型'
	              }
	          ];
	          for (const validation of validations) {
	              if (validation.condition) {
	                  this.$message({
	                      message: validation.message,
	                      type: 'warning'
	                  });
	                  return false;
	              }
	          }
	          return true;
	      },
	      // 生成题号范围
	      generateQuestionNumbers(start, end) {
	          try {
	              const startNum = parseInt(start, 10);
	              const endNum = parseInt(end, 10);
	  
	              if (isNaN(startNum) || isNaN(endNum)) {
	                  throw new Error('无效的题号范围');
	              }
	              if (startNum > endNum) {
	                  throw new Error('起始题号不能大于结束题号');
	              }
	              const numArray = [];
	              for (let i = startNum; i <= endNum; i++) {
	                  numArray.push(i);
	              }
	              return numArray.join(',');
	          } catch (error) {
	              this.$message.error(error.message);
	              return null;
	          }
	      },
	      // 处理排列方式
	      handleArrangement() {
	          const arrangement = {
	              optionArrangement: '',
	              questionArrangement: '',
	              questionnumberhor: ''
	          };
	  
	          if (this.questiontypemodel.includes(',')) {
	              const [optionArr, questionArr] = this.questiontypemodel.split(',');
	              arrangement.optionArrangement = optionArr;
	              arrangement.questionArrangement = questionArr;
	              arrangement.questionnumberhor = optionArr;
	          } else {
	              arrangement.optionArrangement = this.questiontypemodel;
	              arrangement.questionArrangement = this.questiontypemodel;
	              arrangement.questionnumberhor = this.questiontypemodel;
	          }
	  
	          return arrangement;
	      },
	      // 主方法
	      startCrop() {
	              // 验证输入
			  if (!this.validateInputs()) {
				  return false;
			  }
	  
			  try {
				  // 更新 questionRulesId
				  this.questionnumbercon.questionRulesId = this.questiontype;
	  
				  // 处理题号
				  if (this.questionnumberishow) {
					  const numbers = this.generateQuestionNumbers(
						  this.startselfQuestionumber,
						  this.endselfQuestionumber
					  );
					  if (!numbers) return false;
					  this.questionnumbercon.includedNumbers = numbers;
				  } else {
					  this.questionnumbercon.includedNumbers = this.selfQuestionumber;
				  }
	  
				  // 处理排列方式
				  const arrangement = this.handleArrangement();
				  
				  // 正确的对象属性更新方式
				  this.questionnumbercon.optionArrangement = arrangement.optionArrangement;
				  this.questionnumbercon.questionArrangement = arrangement.questionArrangement;
				  
				  this.questionnumberhor = arrangement.questionnumberhor;
	  
				  // 输出调试信息
				  // //console.info('Generated object:', this.questionnumbercon);
	  
				  // 发送数据到父组件
				  this.$emit('objbasicparameters', this.questionnumbercon);
	  
				  // 开始绘制
				  // this.isDrawing = true;
				  const canvas = this.$refs.markCanvas;
				//   draw(canvas, this.modelarealistcavans, undefined, this.isDrawing);
				  draw(cav, this.modelarealistcavans, undefined, this.isDrawing, (newRectangle) => {
						// 处理新矩形对象
						this.handleNewRectangle(newRectangle);
					});
	  
				  return true;
			  } catch (error) {
				  console.error('Error in startCrop:', error);
				  this.$message.error('处理过程中出现错误，请重试');
				  return false;
			  }
		},
	  qiehuanquestion(){
	  	// //console.info('qiehuanquestion')
	  	this.questionnumberishow=!this.questionnumberishow
	  	this.startselfQuestionumber=''
	  	this.endselfQuestionumber=''
	  	this.selfQuestionumber=''
	  },
	  clearInputValue() {
		this.startselfQuestionumber=''
		this.endselfQuestionumber=''
		this.selfQuestionumber=''
		this.questionclassifylist=[]
	   this.questiontypemodel=''
	   this.questiontype=''
	   this.questionnumberhor={}
	    this.questionnumbercon={}
	  },
    /* 画布初始化 */
    initCanvas(num) {
      const that = this
      this.$nextTick(() => {
        // 初始化canvas宽高
        let cav = that.$refs.markCanvas;
		let ctx = cav.getContext('2d');
		ctx.strokeStyle = '#295CFF'
		cav.style.cursor = 'crosshair'
        const img = that.$refs.imgs;
		if(num==1){
			img.onload = () => {
			  cav.width = img.naturalWidth;
			  cav.height = img.naturalHeight;
			  that.imgHeight = img.naturalHeight;
			  that.imgWidth= img.naturalWidth;
			  let list = that.markList; // 画框数据集合, 用于服务端返回的数据显示和绘制的矩形保存
			  // //console.info('loadimgmarkList',that.markList)
			  // 若list长度不为0, 则显示已标记框
			  if (list.length !== 0) {
			  	// //console.info('dddddd')
			    list.forEach(function (value, index, array) {
					// //console.info('loadimg',value.templatePointType)
			  	  ctx.clearRect(value.x, value.y, value.w, value.h);
					  // 遍历绘制所有标记框
					ctx.beginPath();
					ctx.strokeStyle = '#295CFF';
					ctx.rect(value.x, value.y, value.w, value.h);
					ctx.stroke();
					// 添加透明背景
					ctx.fillStyle = 'rgba(135, 206, 235, 0.2)'; // 设置背景颜色为半透明白色
					ctx.fillRect(value.x, value.y, value.w, value.h); // 填充矩形
					if (value.options && value.options.length > 0) {
						// //console.info(value.options.length);
						value.options.forEach(option => {
							ctx.beginPath();
							ctx.rect(option.x, option.y, option.w, option.h);
							ctx.stroke();
						});
					}
					// 新增题型显示 - 统一样式
					const typeButtonHeight = 24;
					const padding = 20; // 文字左右padding
					
					// 设置文字样式
					ctx.fillStyle = 'white';
					ctx.font = '14px Microsoft YaHei';
					ctx.textAlign = 'center';
					ctx.textBaseline = 'middle';
					
					// 根据templatePointType显示不同内容
					let typeText = '';
					switch(value.templatePointType) {
						case 1: 
							typeText = '定位点';
							break;
						case 2:
							typeText = '文字定位点';
							break;
						case 3:
							typeText = '缺考标记';
							break;
						case 4:
							typeText = '条形码';
							break;
						case 5:
							typeText = '考号填涂';
							break;
						case 6:
							typeText = '客观题';
							break;
						default:
							typeText = '主观题';
					}
					
					// 添加题号
					let name = value.includedNumbers != undefined ? value.includedNumbers : '';
					const displayText = typeText + name;
					
					// 计算文字宽度并添加padding
					const textWidth = ctx.measureText(displayText).width;
					const typeButtonWidth = textWidth + (padding * 2); // 文字宽度加上左右padding
					
					// 绘制文字背景 - 贴着矩形框顶部
					ctx.fillStyle = '#295CFF';
					ctx.fillRect(value.x, value.y - typeButtonHeight, typeButtonWidth, typeButtonHeight);
					
					// 绘制文字 - 调整文字垂直位置，确保居中
					ctx.fillStyle = 'white';
					ctx.fillText(displayText, value.x + typeButtonWidth/2, value.y - typeButtonHeight/2);
							
			    });
				
			  }
			   cav.addEventListener('click', function(event) {
			  	const rect = cav.getBoundingClientRect();
			  	const x = event.clientX - rect.left;
			  	const y = event.clientY - rect.top;
			  	that.handleCanvasClick(x, y);
			  });
			  draw(cav, list, undefined, true, (newRectangle) => {
					// 处理新矩形对象
					that.handleNewRectangle(newRectangle);
				});
			}
		}else{
			cav.width = img.naturalWidth;
			cav.height = img.naturalHeight;
			that.imgHeight = img.naturalHeight;
			that.imgWidth= img.naturalWidth;
			let list = that.markList; // 画框数据集合, 用于服务端返回的数据显示和绘制的矩形保存
			// 若list长度不为0, 则显示已标记框
			if (list.length !== 0) {
				// //console.info('dddddd')
			  list.forEach(function (value, index, array) {
				  //console.info('valeuessss',(value.templatePointType))
				  ctx.clearRect(value.x, value.y, value.w, value.h);
				  // 遍历绘制所有标记框
				ctx.beginPath();
				ctx.strokeStyle = 'blue';
				ctx.rect(value.x, value.y, value.w, value.h);
				ctx.stroke();
				// 添加透明背景
				ctx.fillStyle = 'rgba(135, 206, 235, 0.2)'; // 设置背景颜色为半透明白色
				ctx.fillRect(value.x, value.y, value.w, value.h); // 填充矩形
				if (value.options && value.options.length > 0) {
					// //console.info(value.options.length);
					value.options.forEach(option => {
						ctx.beginPath();
						ctx.rect(option.x, option.y, option.w, option.h);
						ctx.stroke();
					});
				}
				
				// 新增题型显示 - 统一样式
				const typeButtonHeight = 24;
				const padding = 20; // 文字左右padding
				
				// 设置文字样式
				ctx.fillStyle = 'white';
				ctx.font = '14px Microsoft YaHei';
				ctx.textAlign = 'center';
				ctx.textBaseline = 'middle';
				
				// 根据templatePointType显示不同内容
				let typeText = '';
				switch(value.templatePointType) {
					case 1: 
						typeText = '定位点';
						break;
					case 2:
						typeText = '文字定位点';
						break;
					case 3:
						typeText = '缺考标记';
						break;
					case 4:
						typeText = '条形码';
						break;
					case 5:
						typeText = '考号填涂';
						break;
					case 6:
						typeText = '客观题';
						break;
					default:
						typeText = '主观题';
				}
				
				// 添加题号
				let name = value.includedNumbers != undefined ? value.includedNumbers : '';
				const displayText = typeText + name;
				
				// 计算文字宽度并添加padding
				const textWidth = ctx.measureText(displayText).width;
				const typeButtonWidth = textWidth + (padding * 2); // 文字宽度加上左右padding
				
				// 绘制文字背景 - 贴着矩形框顶部
				ctx.fillStyle = '#295CFF';
				ctx.fillRect(value.x, value.y - typeButtonHeight, typeButtonWidth, typeButtonHeight);
				
				// 绘制文字 - 调整文字垂直位置，确保居中
				ctx.fillStyle = 'white';
				ctx.fillText(displayText, value.x + typeButtonWidth/2, value.y - typeButtonHeight/2);
						
			  });
			}
			 cav.addEventListener('click', function(event) {
				const rect = cav.getBoundingClientRect();
				const x = event.clientX - rect.left;
				const y = event.clientY - rect.top;
				that.handleCanvasClick(x, y);
			});
			draw(cav, list, undefined, true, (newRectangle) => {
					// 处理新矩形对象
					that.handleNewRectangle(newRectangle);
				});
		}
      })
    },
	handleNewRectangle(newRectangle) {
      this.$emit('newRectangle', newRectangle);
    },
	// 计算按钮位置
	getButtonPositions(mark) {
		const buttonWidth = 60;
		const buttonHeight = 20;
		const buttonMargin = 5;
		
		const editButtonX = mark.x + mark.w - buttonWidth - buttonMargin;
		const editButtonY = mark.y + mark.h + buttonMargin;
		const deleteButtonX = editButtonX - buttonWidth - buttonMargin;
		const deleteButtonY = editButtonY;
		
		return {
			edit: {
				x: editButtonX,
				y: editButtonY,
				width: buttonWidth,
				height: buttonHeight
			},
			delete: {
				x: deleteButtonX,
				y: deleteButtonY,
				width: buttonWidth,
				height: buttonHeight
			}
		};
	},
	
	// 检查点击是否在按钮区域内
	isClickInButton(x, y, button) {
		return x > button.x && 
			   x < button.x + button.width && 
			   y > button.y && 
			   y < button.y + button.height;
	},
	
	// 处理画布点击
	handleCanvasClick(x, y) {
	  // 检查点击时间间隔
	  const now = Date.now();
	  if (now - this.lastClickTime < this.clickDelay) {
	    return;
	  }
	  this.lastClickTime = now;
	  
	  if (this.isProcessing) return;
	  
	  let list = this.markList;
	  let handled = false;
	  
	  list.some((mark, index) => {
	    if (handled) return true;
	    
	    const buttons = this.getButtonPositions(mark);
	    
	    if (this.isClickInButton(x, y, buttons.edit)) {
	      handled = true;
	      this.handleEdit(mark);
	      return true;
	    }
	    
	    if (this.isClickInButton(x, y, buttons.delete)) {
	      handled = true;
	      this.handleMarkDelete(mark, index);
	      return true;
	    }
	    
	    return false;
	  });
	},
	
	// 处理编辑
	handleEdit(mark) {
		console.info('mark',mark)
	  // 防止重复处理
	  if (this.isProcessing) return;
	  
	  try {
	    this.isProcessing = true;
		let obj = {ishow:true}
		const mergedObj = Object.assign({}, obj, mark);
		this.$emit('editContent',mergedObj)
	    //console.info('编辑按钮被点击', mark); // 添加mark信息以便调试
	    // 这里添加你的编辑逻辑
	  } finally {
	    this.isProcessing = false;
	  }
	},
	
	// 处理删除
	async handleMarkDelete(mark, index) {
		try {
			this.isProcessing = true;
			
			if (mark.id) {
				// 删除服务器数据
				await this.deleteFromServer(mark.id);
			} else {
				// 删除本地数据
				this.deleteLocal(index);
			}
		} finally {
			this.isProcessing = false;
		}
	},
	
	// 从服务器删除
	async deleteFromServer(id) {
		try {
			const res = await dele('/template/cuttingregion/delete', 
				{ id },
				{
					headers: {
						'Content-Type': 'x-www-form-urlencoded',
					}
				}
			);
			
			if (res.code === 200) {
				this.$message.success('删除成功');
				this.$emit('refreshdata');
			} else {
				throw new Error(res.message || '删除失败');
			}
		} catch (error) {
			console.error('Delete error:', error);
			this.$message.error(error.message || '删除失败');
			throw error;
		}
	},
	
	// 本地删除
	deleteLocal(index) {
		this.markList.splice(index, 1);
		this.$message.success('删除成功');
	}
  },
 beforeDestroy() {
    // 移除事件监听器
    document.removeEventListener('customMouseDown',(event)=>{})
  }
}
</script>
<style scoped>
.content {
  position: relative;
}
.img {
    position: absolute;
    top: 0;
    left: 0;
    object-fit: contain;
    z-index: 9;
  }

  canvas {
    position: absolute;
    top: 0;
    left: 0;
    z-index: 10;
  }
  .routate{
	  box-sizing: border-box;
	  width:480px;
  	position:fixed;
  	left:25px;
  	top:110px;
  	background:#fff;
  	display: flex;
  	align-items: center;
  	padding:0 10px;
  	box-shadow: 0 0 10px rgba(0,0,0,0.4);
  	border-radius:5px;
  	font-size:14px;
  	color:#557292;
  	border-radius: 10px;
	z-index:111;
	flex-wrap: wrap;
	padding:14px;
  }
  .el-select,.el-input{
  	width:100px;
  }
  .el-select{
  	margin-right:10px;
  	margin-left:10px;
  }
  .el-input{
  	margin-left:10px;
  	margin-right:10px;
  }
   .routate >>> .el-button{
  	border-radius:10px;
  	height:35px;
  	padding:0 10px;
  }
  .routate >>> .el-input__inner{
  	border-radius:10px;
  	height:35px;
  }
  .questiontypemodel{
	  width:220px;
	  height:34px;
  }
   .questiontypemodel >>> .el-input__inner{
  	border-radius:10px;
  	height:34px;
  }
  .routateboxsetlist{
	  width:100%;
	  display: flex;
	  justify-content: space-between;
  }
  .questionshowhidden{
	  display: flex;
	  line-height:40px;
	  margin-bottom:14px;
  }
  .questionshowhidden img{
	 width:14px;
	  height:14px;
	  margin-top:13px;
	  margin-right: 3px;
  }
.twoinputbox{
	display: flex;
	align-items: center;
}
.twoinputbox  >>> .el-input{
	width: 50px;
	height: 34px;
	padding:0;
}
  .twoinputbox  >>> .el-input__inner{
	  width: 50px;
	  height: 34px;
	  background:none;
	  border-radius: 10px;
	  padding:0;
	  text-align: center;
  }
  .twoinputbox  >>> .el-input__icon{
      line-height:34px;
  }
  .dangeinput >>> .el-textarea{
	  width:150px;
  }
  .dangeinput >>> .el-input__inner{
	  width:150px;
	  height:100px;
  }
  .routateboxsetlist  >>> .el-input__icon{
      line-height:34px;
  }
</style>